import { Notification } from 'element-ui'
import { getToken } from '@/framework/utils/auth' // get token from cookie
import {
  yesOrNotUnReadMessage
} from '@/framework/api/message'

export default {

  namespaced: true,
  state: {
    websock: null,
    url: '',
    lockReconnect: false, // 是否真正建立连接
    timeout: 25 * 1000, // 25秒一次心跳
    timeoutObj: null, // 心跳心跳倒计时
    serverTimeoutObj: null, // 心跳倒计时
    timeoutnum: null, // 断开 重连倒计时
    message: {},
    isUnReadMessage: null // 是否有未读消息
  },
  getters: {
    message(state) {
      return state.message
    }
  },
  mutations: {
    WEBSOCKET_INIT(state, url) {
      const that = this
      state.websock = new WebSocket(url)
      state.url = url
      state.websock.onopen = function () {
        // state.websock.send('id:123')
        // state.websock.send('OpenBarScanner')
        // 发送心跳包
        that.commit('websocket/start')
      }
      state.websock.onmessage = function (callBack) {
        that.commit('websocket/reset')
        if (callBack.data == '') {
          return
        }
        state.message = callBack.data
        const newmsg = JSON.parse(callBack.data)
        if (callBack.data && newmsg.data && newmsg.data.messageId) {
          Notification.info({
            title: '消息',
            dangerouslyUseHTMLString: true,
            message: '<div style="color:blue;text-decoration:underline;cursor:pointer">您有一条新消息</div>',
            // duration: 0,
            onClick() {
              this.$messageDialog({
                messageId: newmsg.data.messageId
              })
            }
          })
          yesOrNotUnReadMessage()
            .then((res) => {
              state.isUnReadMessage = res.data
            })
        }
      }
      state.websock.οnerrοr = function () { // e错误
        that.commit('websocket/reconnect')
      }
      state.websock.onclose = function () { // e关闭
        // 如果
        const hasToken = getToken()
        if (hasToken) {
          that.commit('websocket/reconnect')
        }
      }
    },
    WEBSOCKET_SEND(state, message) {
      state.websock.send(message)
    },
    reconnect(state) { // 重新连接
      const that = this
      if (state.lockReconnect) {
        return
      }
      state.lockReconnect = true
      // 没连接上会一直重连，设置延迟避免请求过多
      state.timeoutnum && clearTimeout(state.timeoutnum)
      state.timeoutnum = setTimeout(() => {
        // 新连接
        that.commit('websocket/WEBSOCKET_INIT', state.url)
        state.lockReconnect = false
      }, 5000)
    },
    reset(state) { // 重置心跳
      // 清除时间
      clearTimeout(state.timeoutObj)
      clearTimeout(state.serverTimeoutObj)
      // 心跳
      this.commit('websocket/start')
    },
    start(state) { // 开启心跳
      const that = this
      state.timeoutObj && clearTimeout(state.timeoutObj)
      state.serverTimeoutObj && clearTimeout(state.serverTimeoutObj)
      state.timeoutObj = setTimeout(() => {
        // 这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (state.websock.readyState == 1) { // 如果连接正常
          let data = []
          data = '{"clientMsgType":"299999"}'
          state.websock.send(data)
          state.serverTimeoutObj = setTimeout(() => {
            // 超时关闭
            state.websock.close()
          }, state.timeout)
        } else { // 否则重连
          that.commit('websocket/reconnect')
        }
      }, state.timeout)
    },
    SET_ISUNREADMESSAGE(state, data) {
      if (data > 0) {
        state.isUnReadMessage = data
      } else {
        state.isUnReadMessage = null
      }
    }
  },
  actions: {
    WEBSOCKET_INIT({
      commit
    }, url) {
      commit('WEBSOCKET_INIT', url)
    },
    WEBSOCKET_SEND({
      commit
    }, message) {
      commit('WEBSOCKET_SEND', message)
    },
    setIsUnReadMessage({ commit }, data) {
      commit('SET_ISUNREADMESSAGE', data)
    }

  }
}
